package com.yangcangclub.commons.utils;


import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;


/**
 * 向客户端响应数据格式服务类
 */
public class HttpServletUtil {
    private static Map<String, String> contentMap = new HashMap<String, String>();

    static {
        contentMap.put("xml", "text/xml;charset=");
        contentMap.put("json", "text/json;charset=");
        contentMap.put("xml_utf8", "text/xml;charset=UTF-8");
        contentMap.put("json_utf8", "application/json;charset=UTF-8");
        contentMap.put("html_utf8", "text/html;charset=UTF-8");
    }

    public static void WriteXml(HttpServletResponse response, String writeText) throws Exception {
        write(response, writeText, "xml_utf8");
    }

    public static void WriteHtml(HttpServletResponse response, String writeText) throws Exception {
        write(response, writeText, "html_utf8");
    }

    public static void WriteXml(HttpServletResponse response, String writeText, String charset) throws Exception {
        write(response, writeText, "xml", charset);
    }

    public static void WriteJSON(HttpServletResponse response, String writeText) throws Exception {
        write(response, writeText, "json_utf8");
    }

    public static void WriteJSON(HttpServletResponse response, String writeText, String charset) throws Exception {
        write(response, writeText, "json", charset);
    }

    private static void write(HttpServletResponse response, String writeText, String contentType) throws Exception {
        write(response, writeText, contentType, "");
    }

    private static void write(HttpServletResponse response, String writeText, String contentType, String charset) throws Exception {
        response.setContentType(contentMap.get(contentType) + charset);
        PrintWriter out = response.getWriter();
        out.write(writeText);//
        out.flush();
        out.close();
    }


    /**
     * 获取浏览器类型
     * @return
     */
    public static String getExploreType(HttpServletRequest request){
        if(request==null||request.getHeader("User-Agent")==null)return "likesharing";
 
        String ua=request.getHeader("User-Agent");
        //注意判断顺序
        if(ua.contains("MicroMessenger"))return "weixin";
        if(ua.contains("QQ"))return "qq";
        if(ua.contains("MSIE"))return "ie";
        if(ua.contains("Firefox"))return "firefox";
        if(ua.contains("UBrowser"))return "uc";
        if(ua.contains("Android")||ua.contains("Linux"))return "android";
        if(ua.contains("iPhone"))return "iphone";
        if(ua.contains("iPad"))return "ipad";
        if(ua.contains("Presto"))return "opera";
        if(ua.contains("Chrome"))return "chrome";
        if(ua.contains("Safari"))return "safari";
        if(ua.contains("AppleWebKit"))return "safari";
        
        return "likesharing";
    }

}
